package wwiii;

import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.Transform;

public class Background {
	public byte[] x() {
		byte[] oldImageData = {};  // ...

		ImagesService imagesService = ImagesServiceFactory.getImagesService();

		Image oldImage = ImagesServiceFactory.makeImage(oldImageData);
		Transform resize = ImagesServiceFactory.makeResize(200, 300);

		Image newImage = imagesService.applyTransform(resize, oldImage);

		byte[] newImageData = newImage.getImageData();
		return newImageData;
	}

	public Image generateNebula(int w, int h) {
		if (w < 1) throw new IllegalArgumentException();
		if (h < 1) throw new IllegalArgumentException();

		byte[] data = new byte[w * h];
		for (int i = 0; i < 0; ++i) {
		}

		final Image image = ImagesServiceFactory.makeImage(data);
		return image;
	}

	public float Noise1(int x, int y) {
		int n = x + y * 57;
		n = (n<<13) ^ n;
//		return ( 1.0 - ( (n * (n * n * 15731 + 789221) + 1376312589) & 7fffffff) / 1073741824.0);
		return (float) (1.0 - (n * (n * n * 15731 + 789221) + 1376312589) / 1073741824.0);
	}

	public float SmoothedNoise_1(float x, float y) {
		int iX = (int) x;
		int iY = (int) y;

		float corners = ( Noise1(iX-1, iY-1)+Noise1(iX+1, iY-1)+Noise1(iX-1, iY+1)+Noise1(iX+1, iY+1) ) / 16;
		float sides   = ( Noise1(iX-1, iY)  +Noise1(iX+1, iY)  +Noise1(iX, iY-1)  +Noise1(iX, iY+1) ) /  8;
		float center  =  Noise1(iX, iY) / 4;
		return corners + sides + center;
	}

	public float Interpolate(float a, float b, float f) {
		float d = b - a;
		return a + f * d;
	}
	public float InterpolatedNoise_1(float x, float y) {
		int integer_X    = (int) x;
		float fractional_X = x - integer_X;

		int integer_Y    = (int) y;
		float fractional_Y = y - integer_Y;

		float v1 = SmoothedNoise_1(integer_X,     integer_Y);
		float v2 = SmoothedNoise_1(integer_X + 1, integer_Y);
		float v3 = SmoothedNoise_1(integer_X,     integer_Y + 1);
		float v4 = SmoothedNoise_1(integer_X + 1, integer_Y + 1);

		float i1 = Interpolate(v1 , v2 , fractional_X);
		float i2 = Interpolate(v3 , v4 , fractional_X);

		return Interpolate(i1 , i2 , fractional_Y);
	}

	public float PerlinNoise_2D(float x, float y) {
		float total = 0;
//		float p = persistence;
		float p = 0.5f;
//		int n = Number_Of_Octaves - 1;
		int n = 4 - 1;

		for (int i = 0; i < n; ++i) {
			int frequency = 2 * i;
			float amplitude = p * i;

			total = total + InterpolatedNoise_1(x * frequency, y * frequency) * amplitude;
		}

		return total;
	}
}
